package cn.wolfcode.util;

import cn.wolfcode.domain.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class ControllerExceptionHandler {
    @ExceptionHandler(RuntimeException.class)
    public String handlerException(RuntimeException e, HandlerMethod handlerMethod,
                                   HttpServletResponse response) throws IOException {
        e.printStackTrace();
        //判断当前执行的方法是否是ajax的方法(@ResponseBody)
        if(handlerMethod.hasMethodAnnotation(ResponseBody.class)){
            JsonResult json = new JsonResult(false,"操作失败");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(json));
            return null;
        }
        //如果不是,则返回错误视图
        return "/common/error";
    }

    @ExceptionHandler(UnauthorizedException.class)
    public String handlerUnauthorizedException(RuntimeException e, HandlerMethod handlerMethod,
                                   HttpServletResponse response) throws IOException {
        e.printStackTrace();
        //判断当前执行的方法是否是ajax的方法(@ResponseBody)
        if(handlerMethod.hasMethodAnnotation(ResponseBody.class)){
            JsonResult json = new JsonResult(false,"操作失败");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(json));
            return null;
        }
        //如果不是,则返回错误视图
        return "/common/nopermission";
    }
}
